package com.xmjs.baselibrary.network.converter;

import com.alibaba.fastjson.JSON;
import com.xmjs.baselibrary.network.ResponseBean;
import com.xmjs.baselibrary.network.ResponseError;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private final Type type;

    FastJsonResponseBodyConverter(Type type) {
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String json = value.string();
        ResponseBean bean = JSON.parseObject(json, ResponseBean.class);

        //请求码等于200表示请求成功（具体根据实际的接口业务来定），直接返回data层实体数据就好
        if (bean.getCode() == 200) {
            //如果返回的data为null时处理成空字符串
            if (type == String.class && bean.getData() == null) {
                bean.setData("");
                return (T) bean.getData();
            }
            return JSON.parseObject(bean.getData(), type);
        }
        //请求码不等于200表示请求失败，返回封装好的表示错误的实体数据
        throw new ResponseError(bean);
    }
}
